package com.tanhua.server.service;

import cn.hutool.core.convert.Convert;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.Video;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.vo.FollowUser;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public ResponseEntity saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、封面图上传到阿里云OSS，获取地址
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //2、视频上传到fdfs上，获取请求地址
        //获取文件的后缀名
        String filename = videoFile.getOriginalFilename();  //ssss.avi
        String sufix = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), sufix, null);//文件输入流，文件长度，文件后缀，元数据
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //3、创建Video对象，并设置属性
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API完成保存
        videoApi.save(video);
        //5、构造返回值
        return ResponseEntity.ok(null);
    }

    public PageResult queryVideoList(Integer page, Integer pagesize) {
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisData = (String) this.redisTemplate.opsForValue().get(redisKey);
        PageResult result;
        if (StringUtils.isEmpty(redisData)) {
            //1、调用API查询分页数据 PageResult<Video>
            result = videoApi.findAll(page, pagesize, Collections.EMPTY_LIST);
        } else {
            String[] split = redisData.split(",");
            if ((page - 1) * pagesize > split.length) {
                return new PageResult();
            }
            List<Long> vids = Arrays.stream(split)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize)
                    .map(e -> Convert.toLong(e))
                    .collect(Collectors.toList());
            result = videoApi.findAll(page, pagesize, vids);
        }

        //2、获取分页对象中list集合  List<Video>
        List<Video> items = (List<Video>) result.getItems();
        //3、一个Video转化成一个VideoVo对象
        List<VideoVo> list = new ArrayList<>();
        String key = Constants.FOCUS_USER + UserHolder.getUserId();
        for (Video item : items) {
            UserInfo info = userInfoApi.findById(item.getUserId());
            VideoVo vo = VideoVo.init(info, item);
            //加入了作者关注功能，从redis判断是否存在关注的key，如果存在设置hasFocus=1
            String hashKey = String.valueOf(item.getUserId());
            if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                vo.setHasFocus(1);
            }
            list.add(vo);
        }
        //4、替换PageResult中的list列表
        result.setItems(list);
        //5、构造返回值
        return result;
    }

    public void userFocus(Long followUserId) {
        //1、创建FollowUser对象，并设置属性
        FollowUser followUser = new FollowUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        //2、调用API保存
        videoApi.saveFollowUser(followUser);
        //3、将关注记录存入redis中
        String key = Constants.FOCUS_USER + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }

    public void userUnFocus(Long followUserId) {
        //1、调用API删除关注数据
        videoApi.disSaveFollowUser(UserHolder.getUserId(), followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key, hashKey);
    }
}